<!-- 红黑榜页面  王清林 -->
<template>
    <div class="ranking-page">
        <!-- 头部 -->
        <div class="header">
            <div class="title">黑猫投诉企业服务榜单</div>
            <div class="subtitle">依照企业在本平台中的投诉解决情况得出</div>
            <van-button size="small" type="default" class="rule-btn" @click="showRule = true">
                榜单规则
            </van-button>
        </div>

        <!-- 主标签页 -->
        <van-tabs
            v-model:active="activeMainTab"
            animated
            @change="onMainTabChange"
            scrollable
            :key="activeMainTab"
        >
            <!-- “全部”标签：显示所有分类的卡片 -->
            <van-tab title="全部" name="all">
                <!-- 子标签页 -->
                <van-tabs v-model:active="activeSubTab" animated @change="onSubTabChange">
                    <van-tab title="红榜" name="red"></van-tab>
                    <van-tab title="黑榜" name="black"></van-tab>
                    <van-tab title="回复效率" name="efficiency"></van-tab>
                </van-tabs>

                <!-- 双列卡片布局 -->
                <div class="list-container">
                    <div
                        v-for="tab in filteredMainTabs"
                        :key="tab.tid"
                        class="item-card"
                        @click="gotoMainTab(tab.tid)"
                    >
                        <div class="card-header">
                            {{ tab.tname }}
                            <van-icon name="arrow" />
                        </div>
                        <div class="card-body">
                            <van-cell
                                v-for="(item, i) in getItems(tab.tid)"
                                :key="i"
                                :border="false"
                                clickable
                                class="cell-item"
                                @click.stop="gotoCompanyPage(item)"
                            >
                                <template #title>
                                    <div class="cell-title-content">
                                        <span class="rank">{{ i + 1 }}</span>
                                        <img
                                            :src="getLogoUrl(item.logo)"
                                            alt=""
                                            class="logo"
                                            @error="onImageError"
                                        />
                                        <span class="company-name">{{ item.name }}</span>
                                    </div>
                                </template>
                            </van-cell>
                            <div v-if="getItems(tab.tid).length === 0" class="empty-item">
                                暂无数据
                            </div>
                        </div>
                    </div>

                    <!-- 无数据提示 -->
                    <div
                        v-if="
                            filteredMainTabs.length > 0 &&
                            filteredMainTabs.every((t) => getItems(t.tid).length === 0)
                        "
                        class="empty"
                    >
                        暂无任何数据
                    </div>
                    <div v-if="filteredMainTabs.length === 0" class="empty">
                        暂无分类数据
                    </div>
                </div>
            </van-tab>

            <!-- 动态主标签：每个分类显示为简洁列表 -->
            <template v-for="tab in filteredMainTabs" :key="tab.tid">
                <van-tab :title="tab.tname" :name="tab.tid.toString()">
                    <!-- 子标签页 -->
                    <van-tabs v-model:active="activeSubTab" animated @change="onSubTabChange">
                        <van-tab title="红榜" name="red"></van-tab>
                        <van-tab title="黑榜" name="black"></van-tab>
                        <van-tab title="回复效率" name="efficiency"></van-tab>
                    </van-tabs>

                    <!-- 简洁列表 -->
                    <div class="simple-list">
                        <van-cell
                            v-for="(item, i) in getItems(tab.tid)"
                            :key="i"
                            :border="false"
                            clickable
                            class="cell-item"
                            @click="gotoCompanyPage(item)"
                        >
                            <template #title>
                                <div class="cell-title-content">
                                    <span class="rank">{{ i + 1 }}</span>
                                    <img
                                        :src="getLogoUrl(item.logo)"
                                        alt=""
                                        class="logo"
                                        @error="onImageError"
                                    />
                                    <span class="company-name">{{ item.name }}</span>
                                </div>
                            </template>
                        </van-cell>
                        <div v-if="getItems(tab.tid).length === 0" class="empty-item">
                            暂无数据
                        </div>
                    </div>
                </van-tab>
            </template>
        </van-tabs>

        <!-- 榜单规则弹窗 -->
        <van-popup v-model:show="showRule" round position="bottom" :style="{ height: '40%' }">
            <div class="popup-content">
                <h3>榜单规则</h3>
                <p>根据企业近30天投诉解决率、响应速度等维度综合评分。</p>
            </div>
        </van-popup>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getMainTabs, getRankingData } from '@/api'

// 路由对象
const router = useRouter()

// 后端基础 URL
const BACKEND_URL = 'http://localhost:9977'

// 图片路径处理函数
const getLogoUrl = (logoPath) => {
    if (!logoPath) return `${BACKEND_URL}/upload/default-avatar.png`
    if (logoPath.startsWith('http')) return logoPath
    return `${BACKEND_URL}${logoPath}`
}

// 主标签列表
const mainTabs = ref([
    { tid: 'all', tname: '全部' }
])

// 当前选中的标签
const activeMainTab = ref('all')
const activeSubTab = ref('red')
const showRule = ref(false)

// 榜单数据缓存
const rankingData = ref({})

// 过滤出除 'all' 外的分类
const filteredMainTabs = computed(() => {
    return mainTabs.value.filter(tab => tab.tid !== 'all')
})

// 获取当前子标签下的企业列表
const getItems = (tid) => {
    return rankingData.value[tid]?.[activeSubTab.value] || []
}

// 加载主分类标签
const loadMainTabs = async () => {
    try {
        const res = await getMainTabs()
        if (Array.isArray(res) && res.length > 0) {
            const newTabs = res.map(item => ({
                tid: item.tid,
                tname: item.tname
            }))
            mainTabs.value.push(...newTabs)
        }
    } catch (error) {
        console.error('获取主标签失败:', error.message)
    }
}

// 加载某个分类的榜单数据
const loadRankingData = async (tid) => {
    if (!tid || tid === 'all' || rankingData.value[tid]) return

    try {
        const res = await getRankingData(tid)
        
        if (res && typeof res === 'object' && Array.isArray(res.red) && Array.isArray(res.black) && Array.isArray(res.efficiency)) {
            rankingData.value[tid] = {
                red: res.red || [],
                black: res.black || [],
                efficiency: res.efficiency || []
            }
        } else {
            console.error(`加载 ${tid} 数据失败，响应格式不正确:`, res)
            rankingData.value[tid] = { red: [], black: [], efficiency: [] }
        }
    } catch (error) {
        console.error(`加载 ${tid} 数据失败`, error)
        rankingData.value[tid] = { red: [], black: [], efficiency: [] }
    }
}

// 主标签切换
const onMainTabChange = async (name) => {
    activeMainTab.value = name

    if (name !== 'all') {
        await loadRankingData(name)
    } else {
        for (const tab of filteredMainTabs.value) {
            await loadRankingData(tab.tid)
        }
    }
}

// 子标签切换
const onSubTabChange = () => {
    // 可添加埋点或刷新逻辑
}

// 图片加载失败时使用默认头像
const onImageError = (e) => {
    e.target.src = `${BACKEND_URL}/upload/2025/10/17/company4.jpg`
}

// 跳转到企业详情页（注意阻止事件冒泡）
const gotoCompanyPage = (company) => {
    const companyId = company.id
    if (!companyId) {
        console.log('公司数据中缺少必需的 "id" 参数:', company)
        return
    }
    router.push({
        name: 'companyHome',
        params: { id: companyId },
        query: {
            name: company.name,
            logo: company.logo
        }
    })
}

// ✅ 点击“全部”页中的分类卡片，跳转到对应主标签页
const gotoMainTab = (tid) => {
    if (!tid || activeMainTab.value === tid) return
    activeMainTab.value = tid
    loadRankingData(tid)
    // 可选：滚动到顶部，提升用户体验
    window.scrollTo(0, 0)
}

// 页面初始化
onMounted(async () => {
    await loadMainTabs()
    const firstRealTab = filteredMainTabs.value[0]
    if (firstRealTab) {
        activeMainTab.value = firstRealTab.tid
        await loadRankingData(firstRealTab.tid)
    }
})
</script>

<style scoped>
.ranking-page {
    padding: 16px;
    background-color: #f8f8f8;
    min-height: 100vh;
}

/* 头部样式 */
.header {
    background: linear-gradient(135deg, #FFD700, #FFB347);
    color: white;
    padding: 16px;
    border-radius: 12px;
    margin-bottom: 16px;
    position: relative;
}

.header .title {
    font-size: 18px;
    font-weight: bold;
}

.header .subtitle {
    font-size: 14px;
    opacity: 0.9;
    margin-top: 4px;
}

.rule-btn {
    position: absolute;
    top: 16px;
    right: 16px;
    background-color: rgba(255, 255, 255, 0.2);
    color: white;
    border: none;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
}

/* “全部”页：双列卡片布局 */
.list-container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-top: 16px;
}

.item-card {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: transform 0.1s ease, box-shadow 0.2s ease;
}

.item-card:active {
    transform: scale(0.98);
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.card-header {
    padding: 16px;
    font-size: 16px;
    font-weight: 500;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: px solid #eee;
}

.card-header .van-icon {
    color: #999;
    font-size: 14px;
}

.card-body {
    padding: 12px 16px;
}

/* 企业项样式 */
.cell-item {
    padding: 8px 0;
    border-bottom: 1px solid #eee;
}

.cell-item:last-child {
    border-bottom: none;
}

.cell-title-content {
    display: flex;
    align-items: center;
    width: 100%;
}

.rank {
    width: 20px;
    text-align: center;
    margin-right: 8px;
    color: #999;
    font-size: 12px;
    flex-shrink: 0;
}

.logo {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    object-fit: cover;
    margin-right: 8px;
    flex-shrink: 0;
}

.company-name {
    font-size: 14px;
    color: #333;
    flex: 1;
}

.empty,
.empty-item {
    text-align: center;
    color: #999;
    font-size: 14px;
    padding: 8px 0;
}

.empty {
    grid-column: span 2;
}

/* 单个分类页：简洁列表 */
.simple-list {
    margin-top: 16px;
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.simple-list .cell-item {
    padding: 12px 16px;
}

.simple-list .cell-title-content {
    align-items: center;
}

.simple-list .logo {
    width: 28px;
    height: 28px;
}
</style>